package com.wuhongyu.rabbitmq.consumer.rabbitmq;

import com.rabbitmq.client.Channel;
import com.wuhongyu.api.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class Consumer {


    private RabbitTemplate rabbitTemplate;

    @Autowired
    private void setRabbitTemplate(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = RabbitmqConstant.QUEUE_NAME,
                            arguments = {
                                    @Argument(name = "x-dead-letter-exchange",value = "dlx.exchange")
                            }
                    ),
                    exchange = @Exchange(value = RabbitmqConstant.EXCHANGE,type = "topic"),
                    key = RabbitmqConstant.ROUTEING_KEY,
                    ignoreDeclarationExceptions = "true"


            )
    })
    @RabbitHandler
    public void receive(@Payload Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long del) throws IOException {
        log.info("消费者收到消息： {}", message);
        String type = message.getType();
        if ("error".equals(type)){
            //channel.basicReject(del,false);
            channel.basicNack(del,false,false);
        }else {
            channel.basicAck(del, false);
        }

    }

}
